package com.fighYo.trace.utils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Hashtable;

@Component
@Slf4j
public class QRUtil {

    @Autowired
    private OssUtil ossUtil;

    private final static String CHARSET = "utf-8";

    private final static int QR_WIDTH = 300;

    private final static int QR_HEIGHT = 325;

    private final static int FONTSIZE = 20;

    // 二维码颜色
    private static final int BLACK = 0xFF000000;
    // 二维码颜色
    private static final int WHITE = 0xFFFFFFFF;

    private static final Color QRCOLOR = Color.black; // 二维码颜色 默认是黑色
    private static final Color BGWHITE = Color.white; // 背景颜色

    public BufferedImage createImage(String id) throws Exception {
        String content = id;
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }

        image = addWord(image, content);

        return image;
    }

    private static String outStringByByte(String str, int len) throws IOException {

        byte[] btf = str.getBytes("gbk");
        int count = 0;

        for (int j = len - 1; j >= 0; j--) {
            if (btf[j] < 0) {
                count++;
            } else {
                break;
            }

        }

        if (count % 2 == 0) {
            return new String(btf, 0, len, "gbk");
        } else {
            return new String(btf, 0, len - 1, "gbk");
        }

    }

    public BufferedImage addWord(BufferedImage image, String pressText) throws Exception {

        BufferedImage outImage = new BufferedImage(QR_WIDTH, QR_HEIGHT, BufferedImage.TYPE_INT_RGB);

        //计算文字开始的位置
        //x开始的位置：（图片宽度-字体大小*字的个数）/2
        int startX = (QR_WIDTH - (FONTSIZE * pressText.length())) / 2;
        //y开始的位置：图片高度-（图片高度-图片宽度）/2
        int startY = QR_HEIGHT - (QR_HEIGHT - QR_WIDTH) / 2 + 5;

        int imageW = outImage.getWidth();
        int imageH = outImage.getHeight();
//            BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = outImage.createGraphics();
        g.drawImage(image, 0, 0, imageW, imageH, null);
        g.setColor(QRCOLOR);
        g.setFont(new Font("Times New Roman", Font.PLAIN, FONTSIZE));
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setBackground(Color.white);
//        获取文字数量  按照字节展示
        int size = pressText.getBytes("GBK").length;
//        获取一行最多能容纳多少文字   按照文字字节展示
        int maxSize = (QR_WIDTH / FONTSIZE - 2)*2;
        if (size > maxSize) {
            int v = size % maxSize;
            for (int a = 0; a < (size / maxSize); a++) {
//                g.drawString(pressText.substring(a * maxSize, (a + 1) * maxSize), (WIDTH - (FONTSIZE * maxSize)) / 2 , startY);
                String s = outStringByByte(pressText, maxSize);
                g.drawString(s, (QR_WIDTH - (FONTSIZE * (QR_WIDTH / FONTSIZE - 2))) / 2 , startY);
                pressText=pressText.substring(s.length(),pressText.length());
                startY = startY + 30;
            }
            if (v != 0) {
                g.drawString(pressText, (QR_WIDTH - (FONTSIZE * v)) / 2 , startY);
            }

        } else {
            g.drawString(pressText, (QR_WIDTH - ((pressText.getBytes("GBK").length) / 2) * FONTSIZE) / 2, startY);

        }

        g.dispose();

        return outImage;
    }



    public String createQR(String context) throws Exception {

        BufferedImage image = createImage(context);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ImageIO.write(image, "jpeg", bos);
        MultipartFile multipartFile = new MockMultipartFile("test.jpeg", "test.jpeg", "", bos.toByteArray());

        String url = ossUtil.uploadFile(multipartFile);

        return url;
    }

}
